import http.client
import json
import base64
import datetime
from PIL import Image
import io
import matplotlib.pyplot as plt

def encode_file_base64(file_path):
    with open(file_path,'rb') as f:
        return base64.b64encode(f.read()).decode('utf-8')
    
def decode_file_base64(base64string):
    base64data = base64string.encode('utf-8')
    filedata = base64.b64decode(base64data)
    x = datetime.datetime.now()
    dateTimeStr = x.strftime('%m-%d-%Y-%H-%M-%S')
    with open(f'{dateTimeStr}.png', "wb") as binary_file:
        binary_file.write(filedata)
    

def txt2img():
    message = {      
        "prompt": "cat in a rocket",        
        }
   
    json_data = json.dumps(message)
    return json_data

if __name__ == "__main__":
    conn = http.client.HTTPConnection('localhost:7860')

    headers = {'Content-type': 'application/json'}

    json_data = txt2img()

    conn.request('POST', '/sdapi/v1/txt2img', json_data, headers)

    response = conn.getresponse()
    jstr = response.read().decode()


    json_object = json.loads(jstr)

    image = json_object['images'][0]
    im = Image.open(io.BytesIO(base64.b64decode(image)))
    plt.imshow(im)
    plt.show()
    